package io.clayton.miep.core;

import io.clayton.miep.utils.SystemConstants;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Getter;
import lombok.Setter;

/**
 * 运行时上下文环境信息
 */
public class RuntimeContext {

	public static ServletContext servletContext = null;

	private static ThreadLocal<RuntimeContextWrapper> threadLocal = new ThreadLocal<RuntimeContextWrapper>() {
		protected RuntimeContextWrapper initialValue() {
			return new RuntimeContextWrapper();
		}
	};

	public static SessionBean getSessionBean() {
		return getContextWrapper().getSessionBean();
	}

	public static void setSessionBean(SessionBean bean) {
		getContextWrapper().setSessionBean(bean);
	}

	public static String getRootPath() {
		return (String) servletContext.getAttribute(SystemConstants.ROOT_PATH);
	}

	public static void setRequest(HttpServletRequest request) {
		getContextWrapper().setRequest(request);
	}

	public static HttpServletRequest getRequest() {
		return getContextWrapper().getRequest();
	}
	
	public static void setResponse(HttpServletResponse response) {
		getContextWrapper().setResponse(response);
	}

	public static HttpServletResponse getResponse() {
		return getContextWrapper().getResponse();
	}

	public static void reset() {
		getContextWrapper().reset();
	}

	private static RuntimeContextWrapper getContextWrapper() {
		return threadLocal.get();
	}
	
	@Getter
	@Setter
	private static class RuntimeContextWrapper {
		
		private SessionBean sessionBean;
		private HttpServletRequest request;
		private HttpServletResponse response;
		
		RuntimeContextWrapper() {
			reset();
		}

		public void reset() {
			sessionBean = null;
			request = null;
			response = null;
		}
		
	}
}
